package com.jrx.anytxn.transaction.job.paph.config;


import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.SftpUtils;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.config.PaphFileConfig;
import com.jrx.anytxn.transaction.config.PaphSftpConfig;
import com.jrx.anytxn.transaction.config.VerifyFileConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;

/**
 * @author 张靖烽
 * @name UploadServiceFeeConfiguration
 * @description 上传技术服务费同步分库文件批量
 * @create 2021-03-12 15:53
 **/
@Configuration
@EnableConfigurationProperties(VerifyFileConfig.class)
public class UploadServiceFeeConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(UploadServiceFeeConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private PaphFileConfig paphFileConfig;
    @Autowired
    private PaphSftpConfig paphSftpConfig;

    @Bean
    public Job uploadServiceFeeJob() {
        return jobBuilderFactory.get("uploadServiceFeeJob")
                .start(uploadServiceFeeStep())
                .build();
    }

    @Bean
    public Step uploadServiceFeeStep() {
        return stepBuilderFactory.get("uploadServiceFeeStep")
                .tasklet(uploadServiceFeeTasklet())
                .build();
    }

    @Bean
    @StepScope
    public Tasklet uploadServiceFeeTasklet() {
        return (stepContribution, chunkContext) -> {
            logger.info("》》》》平安普惠服务费文件上传《《《《上传服务费文件开始");
            //1 获取连接
            SftpUtils.sftpConnect(paphSftpConfig.getUsername(), paphSftpConfig.getPassword(), paphSftpConfig.getHost(), paphSftpConfig.getPort());
            // 业务日期
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(TransBizConstant.DEFAULT_ORG_ID);
            String nextProcessingDate = DateFormatUtils.format(org.getNextProcessingDate(), DateUtils.DATE_PATTERN_ANOTHER);
            upload(org.getTenantId(), nextProcessingDate, Constant.PRODECUT_TYPE_XF);
            upload(org.getTenantId(), nextProcessingDate, Constant.PRODECUT_TYPE_JY);
            logger.info("》》》》平安普惠服务费文件上传《《《《上传服务费文件结束");
            //4 关闭连接
            SftpUtils.disSftpConnect();
            return RepeatStatus.FINISHED;
        };
    }

    private void upload(String tenantId, String nextProcessingDate, String product) throws Exception {
        // 消费贷文件路径
        String filePath = paphFileConfig.getServiceFeePath() + tenantId + File.separator + nextProcessingDate + File.separator + product + File.separator;
        // txt md5 文件名
        String txtFileName = Constant.LS_BANK + product + nextProcessingDate + TransBizConstant.SERVICE_FEE_FILE_NAME + ".txt";
        File txtFile = new File(filePath + txtFileName);
        String md5FileName = Constant.LS_BANK + product + nextProcessingDate + TransBizConstant.SERVICE_FEE_FILE_NAME + ".md5";
        File md5File = new File(filePath + md5FileName);
        logger.info("》》》》平安普惠服务费文件上传《《《《XF:path:{},txt:{},md5:{}", filePath, txtFileName, md5FileName);
        if (txtFile.exists() && md5File.exists()) {
            // 检查创建目录
            SftpUtils.createDir(paphSftpConfig.getUploadPath());
            // 上传文件
            SftpUtils.sftpUpload(txtFile);
            SftpUtils.sftpUpload(md5File);
        } else {
            logger.info("》》》》平安普惠服务费文件上传《《《《{}_txt文件或md5文件不存在！", product);
        }
    }
}
